#ifndef _SLMP_DRIVER_
#define _SLMP_DRIVER_

#include <stdio.h> 
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>    	//strlen
#include <cstring>
#include <iostream>

#define ENQ_LEN_SECTER_OFFSET   7
#define MAXDATASIZE 128
#define D_REG_CODE  0xA8
 
enum _select_ex_opt 
{
	eSELECT_NOWAIT       = 0x00000000UL,
	eSELECT_WIAT_FOREVER = 0xffffffffUL,
};

class SLMPDriver
{
public:
	SLMPDriver();
	~SLMPDriver();

	bool SLMPconnect(const char *ip , int port);
	void SLMPclose();
	bool read_bit(int addr,int bit_offset,bool &bitVal);
	bool read_register(int addr, uint16_t &out);
	bool write_bit(int addr,int bit_offset,bool val);
	bool write_register(int addr,uint16_t val);

private:
	int select_read_pend(int fd, uint32_t ms);
	int socketSend(uint8_t* data, uint16_t len);
	int socketRecv(uint8_t* recvbuf, uint16_t &len, uint32_t timeout);
	int sendAndRecv(uint8_t* recv, uint16_t &dataLen);
	void dopackageReadD(uint8_t code, int addr, uint16_t len);
	void dopackageWriteD(uint8_t code, int addr, uint16_t len, uint16_t* val);
	//void dopackageWriteBit(uint8_t code, int addr, uint16_t len,uint8_t* val);
	int responseParser(uint8_t* resp,uint16_t len,uint8_t* out,uint16_t &dataLen);
	
private:
	uint8_t message[128];
	uint16_t messageLen;
	uint8_t comm_header_len;
	int sockfd;	
	//char recvBuf[MAXDATASIZE];
};

#endif

